
// import { asyncComponent } from 'react-async-component';
import Taro from "@tarojs/taro";
import { Runtime } from './runtime';
import {Weh5Runtime} from "./weh5Runtime";
import avatar from "../assets/img/icon_79.png";


export const appName = "建务通";
export const companyName = "建务通"; // 公司名称
export const ServerHost = "http://ynjwt.ynxbgg.net";
// export const ServerHost = "http://192.168.3.163:8093";
export const ImagePrefix = 'http://qiniu.laotangzi.com/weapp/images/';
export const ImageSource = 'web' as 'web' | 'local';
// export const ImageSource = 'local' as 'local' | 'web';
/** 分页初始值 */
export const pageSize = 10;
/** 手机号验证正则 */
export const phoneReg = /^0?(13|14|15|18|17)[\d]{9}$/;
/** 不能以空格开头 */
export const spaceReg = /^[^\s]+/;
/** 不能有中文字符 */
export const zhCNReg = /^[\x00-\xff]*$/;
/** 数字正则 */
export const numberReg = /^[0-9]*$/;
/** 身份证号 */
export const IDCardReg = /d{15}|d{18}/;
export const uploadUrl = "/api/services/app/configuration/Upload";
export const dateFormat = "YYYY-MM-DD";
export const dateTimeFormat = "YYYY-MM-DD HH:mm:ss";
export const timeFormat = "HH:mm:ss";
export const timeShortFormat = "HH:mm";
export const termTime = "YYYY.MM.DD";
export const timeFormat1 = "MM月DD日";
export const servicePhoneNumber = "4009-608-609";

/** 建务通选择框数据 */
export const userSexArr = ['男','女','保密']; // 1 = Man , 2 = Women , 3 = UnKnow
export const educationArr = ['初中及以下','中专/中技','高中','大专','本科','硕士','博士']; // 学历
export const technicalTitleArr = ['工程师','建筑师','结构工程师']; // 职称
export const workExperienceArr = ['不限','1-2年','2年以上']; // 工作经验要求年限
export const workYearsArr = Array.from(Array(100), (v, k) => k).filter(item => item>0); // 工作年限
export const typeOfJobArr = ['不限','挂职','全职','兼职']; // 求职类型
export const typeOfJobObj = {BX:'不限',GZ:'挂职',QZ:'全职',JZ:'兼职'}; // 求职类型
export const monthlyPayArr = ['面议','1000-3000','3000-5000','5000以上']; // 期望薪资
export const qualificationArr = ['一级建造师', '二级建造师','建筑师','结构工程师'];  //执业资格
export const registrationArr = ['初始注册']; // 注册情况
export const majorTypeArr = ['建筑','公路','铁路','民航机场','港口与航道']; //专业类别

export const qualificationsTypeArr  = ['转让','求购','托管','求管']; // 资质类别
export const enterpriseQualificationArr  = ['特级','一级','二级','三级']; // 企业资质等级
export const taxTypesArr = ['个人','个体工商户','法人']; //纳税类型
export const projectPriceArr = ['1-100万','101-200万','301-500万','大于500万']; //价格区间
export const memberTypeArr = ['普通会员','VIP会员','代理商','合伙人']; // 用户类型
export const projectTypeArr = ['政府投资公建项目','政府投资非公建项目','社会民资商业建设项目','社会民资非盈利建设项目']; // 项目类型
export const projectDate = ['半年左右','一年左右','一到两年','两年以上']; // 项目工期
export const typeOfInsuranceArr = ['工程投标保证保险','合同履约保证保险','民工工资支付保证险','工程质量保证保险','业主支付保证保险','设备安装保险',
  '工程预付款保证保险','']; // 工程保函险种
export const natureOfTheFirmArr = ['全民所有制企业(即国有企业)', '集体所有制企业', '联营企业', '三资企业', '私营企业及其他企业']; // 企业性质
export const enterpriseScaleArr = ['1-49人', '50-100人', '大于100人'] // 企业规模

/**
 * 运行环境
 * @param weapp:微信小程序
 * @param h5:微信公众号
 * @param app:APP
 */

//export const platform: 'weapp' | 'weh5' | 'app' = 'weh5';
export const platform = process.env.TARO_ENV
export const getRuntime = (): Runtime => {
  switch (platform) {
    case 'h5':
      return new Weh5Runtime();
    default:
      return new Runtime();
  }
}

export const userSex = (value: number) => {
  value = value || 3
  return userSexArr[value-1]
}
export const typeOfJob = (value: number = 1) => {
  /*value = value || 'BX'
  return typeOfJobObj[value]*/
  value = value-1
  return typeOfJobArr[value]
}

export const partOf = (value?: string, length: number = 18) => {
  value = value || '';
  return value.length <= length ? value : value.substring(0, length) + '...';
}

export const numPartOf = (value?: string, ) => {
  var str = value || "";
  return (str.substr(0, 3) + "****" + str.substr(str.length - 4));
}

export const phoneNumPartOf = (value?: string, ) => {
  var str = value || "";
  return str.substr(0,3)+'****'+(str.substr(str.length - 4));
}

export const cardNumPartOf = (value?: string, ) => {
  var cardNum = value || "";
  // var cardNumber = cardNum.replace(/(.{4})/g, "$1 ")
  return "*** **** **** **** " + cardNum.substr(-4);
}

// 姓名
export const namePartOf = (value?: string, ) => {
  var name = value || "";
  let length = name.length
  if(length === 2){
    return name.substr(0,1)+'*'
  }else if(length===3){
    return name.substr(0,1)+'*'+name.substr(length-1)
  }else {
    return name.substr(0,1)+'**'
  }
}

export const getUploadResult = (response, callback) => {
  if (response && response.success === true) callback(response.result);
};

export const getFile = (fileName) => {
  switch (ImageSource) {
    case 'local':
      return fileName;
    default:
      return ImagePrefix + fileName.replace(/.*\//, '');
  }
}

export const  getAvatar = (src: string) => {
  return src || avatar
}

export const isNumber = (str: string) => {
  let reg = new RegExp(numberReg)
  if(reg.test(str)){
    return true
  }else {
    return false
  }
}

export const isPhone = (str: string) => {
  let reg = new RegExp(phoneReg)
  if(reg.test(str)){
    return true
  }else {
    return false
  }
}
// export const map = asyncComponent({
//   resolve: () => import('../components/public/mapEx')
// });
//
// export const getAvatar = (avatar) => {
//   return avatar ? avatar : getFile(require('../images/avatar.png'));
// }

// 返回几天前或是今天几点几分
export const getSimpleTime = (time: string) => {
  if(!time) return time
  if(time.includes('T') ){ time = time.replace('T',' ') }
  let nowStamp = new Date().getTime()
  let timeFormat = new Date(time)
  let timeStamp = timeFormat.getTime()
  let interval = nowStamp-timeStamp
  let dayStamp = 1000*60*60*24
  let day = Math.floor(interval/dayStamp)
  let hours = timeFormat.getHours()
  let minute = timeFormat.getMinutes()
  if(day>0){ return `${day}天前` }
  else { return `今天${hours}:${minute}` }
}


// 根据时间得到几天几时几分几秒前
export const getTime = (time: string) => {
  let [day,hours,minute,seconds] = [0,0,0,0]
  let nowStamp = new Date().getTime();
  let timeStamp = new Date(time).getTime()
  if(nowStamp<timeStamp){ return time }
  let interval = nowStamp-timeStamp
  let dayStamp = 1000*60*60*24
  day = Math.floor(interval/dayStamp)
  let hoursStamp = interval%dayStamp
  hours = Math.floor(hoursStamp/1000/60/60)
  let minuteStamp = hoursStamp%(1000*60*60)
  minute = Math.floor(minuteStamp/1000/60)
  let secondsStamp = minuteStamp%(1000*60)
  seconds = Math.floor(secondsStamp/1000)
  if(day>0){return `${day}天${hours}小时${minute}分${seconds}秒前` }
  else if(hours>0){return `${hours}小时${minute}分${seconds}秒前` }
  else if(minute>0){return `${minute}分${seconds}秒前`  }
  else {return `${seconds}秒前`}
}

export const subtime = (time: string = '') => {
  time = time?time:''
  let pos = time.indexOf('T')
  if(pos !== -1){
    let temp = time.replace('T', ' ')
    return temp.substr(0, 19)
  }else {
    return time
  }
}

export interface IPage {
  pageIndex: number;
  pageSize: number;
}

/**
 * html文本转纯文本
 * @param HTML html文本
 * @return 纯文本
 * 百度搜来的，好NB的正则啊
 */
export const htmlToText = (HTML) =>
{
  var input = HTML || '';
  // return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ');
  return input.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi,'').replace(/<[^>]+?>/g,'').replace(/\s+/g,' ').replace(/ /g,' ').replace(/>/g,' ');
}

// 配置微信分享
export const getJsApiParam = () => {
  let currentUrl = window.location.href
  let apiUrl = `${ServerHost}/api/Account/getWxJsApiParams?curUrl=${currentUrl}`
  Taro.showLoading({title: '加载中...'})
  fetch(apiUrl, {
    method: 'GET',
    mode: "cors",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    credentials: 'same-origin'
  })
    .then(response => {
      Taro.hideLoading()
      return response.json()
    })
    .then(response => {
      let appId = response.appId
      let timestamp = response.timestamp
      let nonceStr = response.nonceStr
      let signature = response.signature
      this.setState({ wxConfig: response })
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: appId, // 必填，公众号的唯一标识
        timestamp: timestamp, // 必填，生成签名的时间戳
        nonceStr: nonceStr, // 必填，生成签名的随机串
        signature: signature,// 必填，签名
        // jsApiList: ['updateAppMessageShareData','onMenuShareAppMessage'], // 必填，需要使用的JS接口列表
        jsApiList: 'updateAppMessageShareData,onMenuShareTimeline,onMenuShareAppMessage,onMenuShareQQ,onMenuShareWeibo'.split(',')
      });
    })
    .catch(error => {
      console.log(error)
    })
}

export const wxShare = (title: string, desc: string, url: string, imgUrl: string) => {
  // if(!getRuntime().getToken()) { getRuntime().navigateTo('/pages/login/login'); return }
  /*let { item } = this.state
  let url1 = ServerHost+'/m/#/pages/dynamic/detail?id='+item.id
  let title = item.title
  let desc = htmlToText(item.content)
  let imgUrl = item.logo*/
  console.log(title)
  console.log(desc)
  var shareData = {
    title,
    desc,
    imgUrl,
    url: url,
    link: url
  };
  wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
    wx.onMenuShareTimeline(shareData);
    wx.updateAppMessageShareData(shareData);
    wx.onMenuShareQQ(shareData);
    wx.onMenuShareWeibo(shareData);
  });
  // WxShare(url,item.logo,item.title,partOf(item.content, 30))
}




